import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

public class EncapsolateResultSet{
    public static void main(String[] args){
        try{
            //装载Driver类
            Class.forName("com.mysql.jdbc.Driver");
            
            //连接数据库
            String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
            String username = "root";
            String password = "";
            Connection conn = DriverManager.getConnection(url, username, password);
            
            //获取Statement
            Statement stmt = conn.createStatement();
            
            //查询数据库，获取结果集
            String sql = "select * from animals";
            ResultSet rs = stmt.executeQuery(sql);
            
            /******************** 封装结果集 ********************/
            
            //获取元结果集
            ResultSetMetaData rsmd = rs.getMetaData();   
            
            //获取结果表columns个数
            int numberOfColumns = rsmd.getColumnCount();
            
            //使用String[]保存字段名
            String[] columnNames = new String[numberOfColumns];
            for(int i = 0; i < columnNames.length; i++){
                columnNames[i] = rsmd.getColumnName(i + 1);
            }
            
            //使用Map存储每条记录，使用ArrayList存储所有记录
            ArrayList<Map<String, Object>> reList = new ArrayList<Map<String, Object>>();
            while(rs.next()){
                //String存储字段名，Object存储字段对象值
                Map<String, Object> rsMap = new HashMap<String, Object>();
                for(int i = 0; i < columnNames.length; i++){
                    //key
                    String key = columnNames[i];
                    //value
                    Object value = rs.getObject(columnNames[i]);
                    // String value = rs.getString(columnNames[i]);
                    rsMap.put(key, value);
                }
                reList.add(rsMap);
            }
            
            //遍历被封装的结果集
            for(int i = 0; i < reList.size(); i++){
                Map<String, Object> reMap = reList.get(i);
                for(Map.Entry<String, Object> entry : reMap.entrySet()){
                    System.out.print(entry.getValue() + " ");
                }
                System.out.println();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}